package com.rainbow.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

// JDK8函数式接口注解 仅能包含一个抽象方法
@FunctionalInterface
public interface RainbowBaseService<E, ID extends Serializable> {


    public RainbowBaseMapper<E, ID> getBaseMapper();

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    public default E get(ID id) {
        return getBaseMapper().selectById(id);
    }

    /**
     * 获取所有列表
     *
     * @return
     */
    public default List<E> getAll() {
        return getBaseMapper().selectList(new QueryWrapper<>());
    }

    /**
     * 获取总数
     *
     * @return
     */
    public default Integer getTotalCount() {
        return getBaseMapper().selectCount(new QueryWrapper<>());
    }

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    public default int save(E entity) {

        return getBaseMapper().insert(entity);
    }

    /**
     * 修改
     *
     * @param entity
     * @return
     */
    public default int update(E entity) {
        return getBaseMapper().updateById(entity);
    }

    /**
     * 批量保存与修改
     *
     * @param entities
     * @return
     */
    public default int saveOrUpdateAll(Iterable<E> entities) {
        AtomicInteger count = new AtomicInteger(0);
        entities.forEach(v -> {
            getBaseMapper().insert(v);
            count.set(count.get() + 1);
        });
        return count.get();
    }

    /**
     * 删除
     *
     * @param entity
     */
    public default void delete(E entity) {
        getBaseMapper().delete(new QueryWrapper<>());
    }

    /**
     * 根据Id删除
     *
     * @param id
     */
    public default void delete(ID id) {
        getBaseMapper().deleteById(id);
    }

}
